package databaseVersionControl.domain.db.sqlBuilder;

import databaseVersionControl.domain.db.Column;
import databaseVersionControl.domain.db.Table;
import databaseVersionControl.domain.dialect.Dialect;

public class CreateTable implements SqlBuilder {

	private final Table _table;

	public CreateTable(Table table) {
		_table = table;
	}

	@Override
	public String buildSql(Dialect dialect) {

		StringBuilder stringBuilder = new StringBuilder("CREATE TABLE %s (\n");

		for (int i = 0; i < _table.getColumns().size(); i++)
			stringBuilder.append(getColumnSql(dialect, _table.getColumns().get(i), i == _table.getColumns().size() - 1));

		stringBuilder.append(");");

		return String.format(stringBuilder.toString(), _table.getName());
	}

	private String getColumnSql(Dialect dialect, Column column, boolean isLastColumn) {
		StringBuilder stringBuilder = new StringBuilder(column.getName());
		stringBuilder.append(" " + dialect.getType(column.getDataType()));
		stringBuilder.append(column.allowNullValue() ? "" : " NOT NULL");
		if (column.isPrimaryKey()) stringBuilder.append(" PRIMARY KEY");
		stringBuilder.append(isLastColumn ? "\n" : ",\n");
		return stringBuilder.toString();
	}
}
